package com.woniushop.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.woniushop.entity.Address;
import com.woniushop.entity.PageBean;
import com.woniushop.entity.User;
import com.woniushop.service.AddressService;
import com.woniushop.service.imple.AddressServiceImple;
import com.woniushop.utils.ControllerUtils;

/**
 * Servlet implementation class AddressServlet
 */
@WebServlet("/address")
public class AddressServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private AddressService addressService = new AddressServiceImple();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String opr = request.getParameter("opr");
		switch (opr) {
		case "findValidByPage":// 找到没有被禁用的地址
			findValidByPage(request, response);
			break;
		case "add":// 新建地址
			add(request, response);
			break;
		case "setDefault":// 设为默认地址
			setDefault(request, response);
			break;
		case "del":// 删除地址
			del(request, response);
			break;
		case "initUpdate":// 删除地址
			initUpdate(request, response);
			break;
		case "update":// 删除地址
			update(request, response);
			break;
		default:
			break;
		}
	}

	private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				request.setAttribute("msg", "null");
			} else {
				// 获得地址对象
				Map<String, String[]> parameterMap = request.getParameterMap();
				Address address = (Address) ControllerUtils.mapToObject(parameterMap, Address.class);

				// 获得省、市、区名称；
				String provice = request.getParameter("provice");
				String city = request.getParameter("city");
				String area = request.getParameter("area");

				// 补全地址信息
				address.setAinfo(provice + "-" + city + "-" + area + "-" + address.getAinfo());

				// 设置用户id
				address.setUid(loginUser.getUid());

				// 添加地址
				addressService.update(address);

				request.setAttribute("msg", "ok");
			}
		} catch (Exception e) {
			request.setAttribute("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}
		request.getRequestDispatcher("MyAddress.jsp").forward(request, response);
	}

	private void initUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				request.setAttribute("msg", "null");
			} else {
				Integer aid = Integer.parseInt(request.getParameter("aid"));
				Address address = addressService.findOne(aid);
				if (address != null) {
					request.setAttribute("msg", "ok");
					request.setAttribute("address", address);
				} else {
					request.setAttribute("msg", "页面信息已过时，请刷新后再试！");
				}
			}
		} catch (Exception e) {
			request.setAttribute("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}
		request.getRequestDispatcher("updateMyAddress.jsp").forward(request, response);
	}

	private void del(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				map.put("msg", "null");
			} else {
				Integer aid = Integer.parseInt(request.getParameter("aid"));
				if (aid != null && aid > 0) {
					addressService.del(aid);
					map.put("msg", "ok");
				} else {
					map.put("msg", "请刷新页面重试！");
				}
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 设为默认地址
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void setDefault(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				map.put("msg", "null");
			} else {
				Integer aid = Integer.parseInt(request.getParameter("aid"));
				Integer uid = loginUser.getUid();
				if (aid != null && aid > 0) {
					addressService.setDefault(aid, uid);
					map.put("msg", "ok");
				} else {
					map.put("msg", "请刷新页面重试！");
				}
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * 新建地址
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				request.setAttribute("msg", "null");
			} else {
				// 获得地址对象
				Map<String, String[]> parameterMap = request.getParameterMap();
				Address address = (Address) ControllerUtils.mapToObject(parameterMap, Address.class);

				// 获得省、市、区名称；
				String provice = request.getParameter("provice");
				String city = request.getParameter("city");
				String area = request.getParameter("area");

				// 补全地址信息
				address.setAinfo(provice + "-" + city + "-" + area + "-" + address.getAinfo());

				// 设置用户id
				address.setUid(loginUser.getUid());

				// 添加地址
				addressService.add(address);

				request.setAttribute("msg", "ok");
			}
		} catch (Exception e) {
			request.setAttribute("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}
		request.getRequestDispatcher("addMyAddress.jsp").forward(request, response);
	}

	/**
	 * 找到没有被禁用的地址
	 * 
	 * @param request
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	private void findValidByPage(HttpServletRequest request, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		// 创建map用来传递JSON数据
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 获得登录用户
			User loginUser = (User) request.getSession().getAttribute("loginUser");
			if (loginUser == null || loginUser.getUstate() == 2 || loginUser.getUrole() != 3) {
				map.put("msg", "null");
			} else {
				// 创建pageBean
				PageBean pageBean = new PageBean();

				// 获得页码，如果没有页码，则设置页码为1
				String page = request.getParameter("page");
				if (page == null || page.trim().length() == 0 || Integer.parseInt(page) < 1) {
					pageBean.setPage(1);
				} else {
					pageBean.setPage(Integer.parseInt(page));
				}

				// 设置分页大小
				pageBean.setPageSize(5);

				// 设置查询条件
				Address address = new Address();
				address.setUid(loginUser.getUid());
				address.setAstate(4);// astate==4表示查询所有可用地址，包括默认地址

				// 获得分页数据
				List<Address> list = addressService.findValidByPage(pageBean, address);
				map.put("list", list);
				map.put("pageBean", pageBean);
				map.put("msg", "ok");
			}
		} catch (Exception e) {
			map.put("msg", "系统维护中，请稍后再试！");
			e.printStackTrace();
		}

		// 返回JSON
		ControllerUtils.returnJson(map, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
